#!/usr/bin/env groovy

node {
    def MAIN_VERSION = 1
    def SMALL_VERSION = 1
    def group = 'docker.io'
    def nameSpace = "agilebeijing"
    def projectName = "ruoyi-fast"
    def mailList = 'bjlianyu@hotmail.com'
    def branch = BRANCH_NAME
    String version = "${branch}.${MAIN_VERSION}.${SMALL_VERSION}.${BUILD_NUMBER}"
    String latestVersion = "${branch}.latest"
    def images = []
    boolean needPublish = true
    boolean needBuild = true

    stage('Preparation') {
        checkout scm
        if (!needPublish || !needBuild) return

        def JAVAHOME = '/usr/local/java/jdk1.8.0_231/bin:/usr/bin/docker:/usr/local/java/apache-maven-3.6.2/bin'
        env.PATH = "${JAVAHOME}:${env.PATH}"
    }

    stage('Build') {
        if (!needPublish || !needBuild) return

        try {
            sh "mvn clean package -Dmaven.test.skip=true"
        }
        catch (Exception e) {
            mail from: 'jenkins', to: mailList, subject: "[构建失败]<windlass-${branch}>自动构建失败", body: "分支<${branch}>构建失败，尽快修复并重新提交。"
            throw e
        }
        finally {
            // 单元测试
//            junit '**/test-results/**/*.xml'
//            sh "mvn install"
//            sh "mvn jacoco:prepare-agent"
//            sh "mvn jacoco:report"
        }
    }

    stage('BuildImages') {
        if (!needPublish || !needBuild) return

        sh "cp ./target/*.jar ./docker/"
        dir("docker") {
            echo("Build image ${projectName}")
            def img = docker.build("${group}/${nameSpace}/${projectName}:${version}")
            images.push(img)
        }
    }

    stage("Publish") {
        if (!needPublish || !needBuild) return
        dir("docker") {
            sh "echo version=${version} > .env"
            sh "sh ./start.sh"
        }
    }

    stage('PushImages') {
        if (!needPublish || !needBuild) return

        for (i = 0; i < images.size(); i++) {
            def image = images[i]
            echo("Push image:${image.imageName()}")
            image.push()

            //image.tag("${latestVersion}")
            //image.push("${latestVersion}")
        }
    }

    stage("BuildInfo") {
        if (!needPublish) return

        String buildVersion = needBuild ? version : latestVersion
        def description = "构建版本：${buildVersion} \n构建项目：${projectName}"
        currentBuild.description = description
    }

    stage("Clean") {
        if (!needPublish || !needBuild) return
        sh "mvn clean"

//        sh "docker rmi ${group}/${nameSpace}/${projectName}:${latestVersion}"
//        sh "docker rmi ${group}/${nameSpace}/${projectName}:${version}"
    }


}